package cn.com.callback

import cn.com.elite.Util
import cn.com.kh.KHDBConfig
import com.jcraft.jsch.ChannelSftp
import com.jcraft.jsch.Session
import com.jcraft.jsch.SftpATTRS;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.jdbc.core.JdbcTemplate
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest
import org.springframework.web.multipart.MultipartResolver
import org.springframework.web.multipart.commons.CommonsMultipartResolver

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import cn.com.elite.EliteBean
import java.text.SimpleDateFormat
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 *
 * @Title: ApiBPUpload* @Description:深圳宝安排水系统工单图片上传接口--内部接口
 * @author: chieh* @date 2020-11-15 21:28:00
 *
 */

public class ApiBPUpload implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(ApiBPUpload.class);

    private static Session msshSession = null;
    private static ChannelSftp msftp = null;
    private static String Mftp_remoteRoot = null;// 主FTP默认路径
    private static String Mftp_key = null;// 主FTP在NGS中配置文件Key
    private static String downloadPath = null;// 默认临时下载文件路径
    private static String NGS_OuterDomain = null; // NGS文件调用下载通用域

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/plain;charset=UTF-8");
        JdbcTemplate jt = new JdbcTemplate(eliteBean.getDataSource());
        log.debug("request:" + request);

        String filePath = "";
        String outData = "";
        long startTime = System.currentTimeMillis();
        long endTime = 0;

        try {
            NGS_OuterDomain = KHDBConfig.getAPIURL(eliteBean, "NGS-OuterDomain") + "fs/get?file=";

            downloadPath = KHDBConfig.getParam(eliteBean, "APITMF");

            // 加载主备FTP连接配置
            Mftp_key = KHDBConfig.getAPIURL(eliteBean, "Mftp.key");

            String Mftp_host = KHDBConfig.getAPIURL(eliteBean, "Mftp.host");
            String Mftp_username = KHDBConfig.getAPIURL(eliteBean, "Mftp.username");
            String Mftp_password = KHDBConfig.getAPIURL(eliteBean, "Mftp.password");
            String Mftp_port = KHDBConfig.getAPIURL(eliteBean, "Mftp.port");
            Mftp_remoteRoot = KHDBConfig.getAPIURL(eliteBean, "Mftp.remoteRoot");

            msshSession = Util.getjschSession(Mftp_host, Mftp_username, Integer.parseInt(Mftp_port));
            msftp = Util.sftpConnect(Mftp_password, msshSession, 10000);


            JSONArray jsonArray = new JSONArray();
            // json对象
            JSONObject json = new JSONObject();

            SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
            String date = df.format(System.currentTimeMillis());

            String realPath = downloadPath + "/" + date;
            log.debug("小程序附件上传计划存储目录:" + realPath);

            File dir = new File(realPath);
            //文件目录不存在，就创建一个
            if (!dir.isDirectory()) {
                log.debug("文件目录不存在-新建目录");
                dir.mkdirs();
            }

            try {
                MultipartResolver resolver = new CommonsMultipartResolver(request.getSession().getServletContext());
                MultipartHttpServletRequest multipartRequest = resolver.resolveMultipart(request);
                //获取formdata的值
                Iterator<String> iterator = multipartRequest.getFileNames();
                MultipartFile file = multipartRequest.getFile(iterator.next());

                boolean fileSize = checkFileSize(file.getSize(), 20, "M");
                if (fileSize) {

                    String fileName = file.getOriginalFilename();
                    log.debug("上传附件文件名:" + fileName);

                    //真正写到磁盘上
                    String uuid = UUID.randomUUID().toString().replace("-", "");
                    log.debug("临时拼接文件ID:" + uuid);

                    String kzm = fileName.substring(fileName.lastIndexOf("."));
                    log.debug("上传附件拓展名:" + kzm);

                    String filename = uuid + kzm;
                    log.debug("附件存储附件名:" + filename);

                    // 检查文件拓展名是否合法
                    String[] safelist = KHDBConfig.getParam(eliteBean, "SAFE##").split(";");
                    boolean fileSafe = false;
                    for (String s : safelist) {
                        if (kzm.equals(s.toLowerCase())) {
                            fileSafe = true;
                            break;
                        }
                    }

                    if (fileSafe) {

                        File file1 = new File(realPath + "/" + filename);
                        boolean saveFlag = false;
                        OutputStream out = null;
                        try {
                            out = new FileOutputStream(file1);
                            out.write(file.getBytes());
                            saveFlag = true;
                        } catch (Exception e) {
                            log.error("上传附件写入本地异常" + e.getMessage());
                            outData = e.getMessage();
                        } finally {
                            try {
                                out.close();
                            } catch (Exception e) {
                                log.error("关闭上传附件写入本地OutputStream", e);
                            }
                        }

                        if (saveFlag) {
                            boolean uploadFlagm = uploadFile(msftp, Mftp_remoteRoot + "/" + date + "/", filename, realPath + "/" + filename);
                            String result = NGS_OuterDomain + Mftp_key + "@" + date + "/" + filename;
                            result = KHDBConfig.getAPIURL(eliteBean, "WXCallBackURL") + "/ngsapitask_pa/file/apiFileProxy?fileurl=" + result;
                            log.info("上传NGS完成...结果Master：" + uploadFlagm + " NGS文件路径：" + result);

                            json.put("url", result);

                            jsonArray.add(json);
                            endTime = System.currentTimeMillis();
                            outData = result;
                        } else {
                            outData = "上传附件写入本地异常";
                        }

                    } else {
                        outData = "非法文件类型";
                    }

                } else {
                    outData = "附件超出限制";
                }


            } catch (Exception e) {
                log.error("接口处理异常" + e.getMessage());
                outData = "接口处理异常";
            }
        } catch (Exception e) {
            log.error("自动从云客服下载备份录音DownloadRecord出现异常", e);
            outData = e.getMessage();
        } finally {
            try {
                Util.disconnectSftp(msftp, msshSession);
            } catch (Exception e) {
                log.error("关闭SFTP连接资源删除[主]", e);
            }
        }
        return outData;

    }

    public static boolean uploadFile(ChannelSftp sftp, String remotePath, String remoteFileName, String localPath) {
        FileInputStream inf = null;
        boolean uploadFileresult = false;

        try {
            if (remotePath != null && !remotePath.equals("") && remotePath.length() > 0) {
                if (!isDirExistSftp(remotePath, sftp)) {
                    sftp.mkdir(remotePath);
                }

                sftp.cd(remotePath);
            }

            File file = new File(localPath);
            inf = new FileInputStream(file);
            sftp.put(inf, remoteFileName);
            uploadFileresult = true;
        } catch (Exception e) {
            log.error("录音上传SFTP异常", e);
        } finally {

            if (inf != null) {
                try {
                    inf.close();
                } catch (Exception e) {
                    log.error("录音上传SFTP后关闭文件流资源异常", e);
                }
            }
        }

        return uploadFileresult;
    }

    public static boolean isDirExistSftp(String directory, ChannelSftp sftp) {
        try {
            SftpATTRS sftpATTRS = sftp.lstat(directory);
            return sftpATTRS.isDir();
        } catch (Exception e) {
            log.error("处理FTP目录Directory异常:" + directory, e);
            return false;
        }
    }

    public static boolean checkFileSize(Long len, int size, String unit) {
        double fileSize = 0;
        if ("B".equals(unit.toUpperCase())) {
            fileSize = (double) len;
        } else if ("K".equals(unit.toUpperCase())) {
            fileSize = (double) len / 1024;
        } else if ("M".equals(unit.toUpperCase())) {
            fileSize = (double) len / 1048576;
        } else if ("G".equals(unit.toUpperCase())) {
            fileSize = (double) len / 1073741824;
        } else {
            return false;
        }
        if (fileSize > size) {
            return false;
        }
        return true;

    }
}